const app = angular.module("myApp", []);
app.controller('configController',['$scope', '$compile', '$sce', function ($scope, $compile){
    $scope.category = [
        {title:'故障模块',name:"module"},
        {title:'故障分组',name:"group"}
    ];

    $scope.items=[];
    $scope.type=null;

    $scope.loadConfigure = function () {
        getConfigure($scope.type.name,data=>{
            $scope.items = data.map(x=>{
                if(x.indexOf(':')<0){
                    return {
                        category:'',
                        name:x,
                        $onEdited:false
                    }
                }
                let arr = x.split(':',2);
                return ({
                    category:arr[0],
                    name:arr[1],
                    $onEdited:false
                })
            });
            $scope.$apply();
        });
    };

    $scope.appendItem = function () {
        $scope.items.push({
            name:'新条目',
            $onEdited:true
        });
    };

    $scope.saveConfigure = function () {
        let session = neo4jService.getSession();
        let data = $scope.items.map(x=>x.category+':'+x.name);
        let resultPromise = session.run(`merge (a:Configure{ ftype:"${$scope.type.name}"})
         ON CREATE set a.data={jsonStr} ON MATCH set a.data={jsonStr}`,{jsonStr:JSON.stringify(data)});
        resultPromise.then(result => {
            session.close();
            console.info("更新成功。");
            $scope.items.forEach(x=> x.$onEdited=false);
            $scope.$apply();
        });
    };

    $scope.persistItem = $scope.saveConfigure;

    $scope.modifyItem = function (item) {
        item.$onEdited = true;
    };

    $scope.deleteItem = function (index) {
        $scope.items.splice(index,1);
        $scope.saveConfigure();
    };
}]);